package com.yuer.rpc.decodec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    /**
     * Netty编写客户端的实现
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        // 基本步骤

        // 1、创建线程组
//        2、创建客户端启动助手
//        3、设置线程组
//        4、设置客户端通实现为NIO
//        5、创建通道初始化对象(通过)
//        6、向pipeline中添加自定义处理的Handler
//        7、启动客户端，等待链接服务端，同时将一步改为同步
//        8、关闭通道和链接池

        EventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(nioEventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                // 添加解码器
                socketChannel.pipeline().addLast("MessageDecoder",new MessageDecoder());
                // 添加解码器
                socketChannel.pipeline().addLast("MessageEncode",new MessageEncoder());

                // 初始化之后，向 pipeline添加自定义处理的handher
                socketChannel.pipeline().addLast(new NettyClientHandler());
            }
        });

        ChannelFuture connect = bootstrap.connect("127.0.0.1", 9999).sync();

        connect.channel().closeFuture().sync();

        nioEventLoopGroup.shutdownGracefully();


    }
}
